const app = getApp()
const util = require('../../utils/util.js');
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function hex2ab(number, byteLength) {
  var byteLength = byteLength || (number > 0 ? Math.ceil(Math.log(number + 1) / Math.log(256)) : 1);
  var buffer = new ArrayBuffer(byteLength);
  var dataView = new DataView(buffer);
  for (var i = 0; i < byteLength; i++) {
    var digit = (number & (0xff << i * 8)) >> i * 8;
    dataView.setUint8(i, digit);
  }
  return buffer;
}


Page({
  data: {
    devices: [],
    connected: false,
    chs: [],
    conShow: false,//当前是否连接设备
    list: [],
    firstConnectType:false,
    deviceId:''
  },
  onLoad() {
    if (wx.getStorageSync('blueToothType')) {
      this.setData({
        devices: wx.getStorageSync('blueToothList'),
        connected: true,
        name: wx.getStorageSync('blueToothName'),
      })
      console.log(this.data.devices, wx.getStorageSync('blueToothList'))
    } else {
      this.openBluetoothAdapter()
    }

  },
  onShow(){
    if (wx.getStorageSync('blueToothType')) {
      this.setData({
        devices: wx.getStorageSync('blueToothList'),
        connected: true,
        name: wx.getStorageSync('blueToothName'),
        deviceId: wx.getStorageSync('deviceId') ,
        firstConnectType:wx.getStorageSync('firstConnectType'),
      })
      console.log(this.data.devices, wx.getStorageSync('blueToothList'))
    }else{
      this.setData({
        connected: false,
        firstConnectType:wx.getStorageSync('firstConnectType'),
      })
    }
  },
  // 初始化蓝牙模块
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log(res)
        wx.showModal({
          content: '请开启手机蓝牙后再试',
          success: (res) => {
            wx.navigateBack({
              delta: 1
            })
          }

        })
      }
    })
  },
  // 获取本机蓝牙适配器状态。
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        this._discoveryStarted = true
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  // 开始搜寻附近的蓝牙外围设备。
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  // 停止搜寻附近的蓝牙外围设备。
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  // 监听搜索到新设备的事件
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      console.log(JSON.stringify(res))
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        if (device.name.substr(0, 5) == 'ch573' || device.name.substr(0, 4) == 'Pure') {
          const foundDevices = this.data.devices
          const idx = inArray(foundDevices, 'deviceId', device.deviceId)
          const data = {}
          if (idx === -1) {
            data[`devices[${foundDevices.length}]`] = device
          } else {
            data[`devices[${idx}]`] = device
          }

          this.setData(data)
        }

      })
    })
  },
  // 获取在蓝牙模块生效期间所有已发现的蓝牙设备
  getBluetoothDevices: function () {
    var that = this
    wx.getBluetoothDevices({
      success: function (res) {
        console.log('获取蓝牙设备成功:' + res.errMsg);
        console.log(res.devices);
        that.clearOtherDevices(res);
      },
      fail: function (res) {
        console.log('获取蓝牙设备错误，错误码：' + res.errMsg);
        if (res.errCode != 0) {
          initTypes(res.errCode);
        }
      }
    })
  },

  // 连接蓝牙低功耗设备
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    console.log(e)
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        wx.showLoading({
          title: '蓝牙正在连接中...',
        })
        wx.setStorageSync('blueToothType', true)
        wx.setStorageSync('blueToothName', name)
        wx.setStorageSync('blueToothIsOpen', true) //设置首页蓝牙状态为true
        // wx.setStorageSync('blueToothList', this.data.devices)
        console.log(this.data.devices)
        this.setData({
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },

  // 获取蓝牙低功耗设备所有服务 (service)。
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log(res.services)
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[1].uuid)
            return
          }
        }
      }
    })
  },
  // 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', serviceId, res)

        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            // 读取蓝牙低功耗设备特征值的二进制数据。
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              success: res => {
                console.log(res)
              },
              fail: res => {
                console.log(res)
              }
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            setTimeout(() => {
              this.writeBLECharacteristicValue()
              this.writeMsg('0x5c0x01')
              // this.writeMsg('0x5c0x03')
              this.writeUnbound()
            }, 2500)

          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
              success: function (res) {
                // 操作之前先监听，保证第一时间获取数据
                console.log(res)


              },
              fail: res => {
                console.log(res)
              }
            })
          }

        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    wx.onBLECharacteristicValueChange((res) => {
      let str = ab2hex(res.value)
      console.log(ab2hex(res.value))
      if (str.slice(0, 2) == '53') {
        wx.setStorageSync('blueToothData', this.splitBlueStr(str))
      }
      if (str.slice(0, 4) == '5101' && str.length == 30) {
        getApp().globalData.blueToothList = this.splitString(str)
      }
      if(str.slice(0, 2) == '55'){
        console.log(this.splitBlueStr(str))
      }

    })
  },
  nextBlueDetail: function () {
    wx.navigateTo({
      url: '../detail/detail'
    })
  },
  string2buffer(str) {
    let val = ""
    for (let i = 0; i < str.length; i++) {
      val += ',' + code2utf8(str.charCodeAt(i))
    }
    val += ',00';
    console.log(val);
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  },

  // 向蓝牙设备发送一个0x00的16进制数据
  writeBLECharacteristicValue() {
    // let hex = this.string2buffer('0x600x00')
    let hex = this.string2buffer('0x560x01')
    console.log(this._deviceId, this._serviceId, this._characteristicId, hex)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: hex,
      success: res => {
        console.log(res)
        wx.setStorageSync('deviceId', this._deviceId)
        wx.setStorageSync('serviceId', this._serviceId)
        wx.setStorageSync('characteristicId', this._characteristicId)
        wx.setStorageSync('firstConnectType',true)
        wx.hideLoading()
        console.log(this.data.devices,util.onDelete(this.data.devices,this.data.name),1111)
        this.setData({
          connected: true,
          devices:util.onDelete(this.data.devices,this.data.name),
          deviceId:this._deviceId,
          firstConnectType:true
        })
        setTimeout(()=>{
          wx.navigateBack({
            delta:1
          })
        },1000)
        

      },
      fail: res => {
        console.log(res)
      }
    })
  },

  // 绑定设备
  writeMsg(str){
    let hex = this.string2buffer(str)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: hex,
      success: res => {
        console.log(res)
        
      },
      fail: res => {
        console.log(res)
      }
    })
  },
  // 解绑设备
  writeUnbound(){
    let hex = this.string2buffer('0x5c0x00')
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: hex,
      success: res => {
        console.log(res)
      },
      fail: res => {
        console.log(res)
      }
    })
  },
  // 校验设备
  writebound(){
    let hex = this.string2buffer('0x5c0x03')
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: hex,
      success: res => {
        console.log(res)
      },
      fail: res => {
        console.log(res)
      }
    })
  },


  // 将数据转成16进制
  string2buffer(str) {
    let val = ""
    if (!str) return;
    let length = str.length;
    let index = 0;
    let array = []
    while (index < length) {
      array.push(str.substring(index, index + 2));
      index = index + 2;
    }
    val = array.join(",");
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  },
  //切割从蓝牙接收到的数据并转为10进制
  splitString(str) {
    let arr = []
    let newTring = str.replace(/(.{2})/g, '$1,').split(',')
    newTring.pop()
    for (let i = 0; i < newTring.length; i++) {
      if (i == 3 || i == 9) {
        let x = '0x' + newTring[i] + newTring[i + 1]
        // console.log(x,Number(x).toString(10))
        arr.splice(i + 1, 1);
        arr.push(Number(x).toString(10))
      } else {
        let x = '0x' + newTring[i]
        arr.push(Number(x).toString(10))
      }
    }
    arr.splice(4, 1);
    arr.splice(10, 1);
    return arr
  },
  //解析设备编号
  splitBlueStr(str) {
    let arr = []
    let newTring = str.replace(/(.{2})/g, '$1,').split(',')
    newTring.pop()
    for (let i = 0; i < newTring.length; i++) {
      let x = '0x' + newTring[i]
      arr.push(Number(x).toString(10))
    }
    return arr
  },
  onPullDownRefresh: function () {

    wx.showNavigationBarLoading()
    this.openBluetoothAdapter()
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 2000);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  senMsg: function () {
    this.writeBLECharacteristicValue()
  },
  onUnload: function () {
    console.log('离开当前页面')
    wx.offBLECharacteristicValueChange((res) => {
      console.log(res, '离开当前页面')
    })
  },
  // 断开与蓝牙低功耗设备的连接。
  closeBLEConnection() {
    this.writeUnbound()
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    wx.closeBluetoothAdapter()
    this.closeBluetoothAdapter()
    wx.removeStorageSync('blueToothName')
    wx.setStorageSync('blueToothType',false)
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  // 关闭蓝牙模块。
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },

})